import { inRange, isRangesCollide } from "./utils.js";

/**
 *
 * @param {number} x
 * @param {number} y
 * @returns
 */
export function Point( x, y ) {
    return { x: x, y: y };
}

export class RoundRectangle {
    /**
     *
     * @param {number} x
     * @param {number} y
     * @param {number} length the expanding in x
     * @param {number} width the expanding in y
     * @param {number} radius the radius of rounding circle
     * @param {*} color
     *
     */
    constructor( x, y, length, width, radius, color ) {
        // console.log(x, y, length, width, radius, color);
        this.x = x;
        this.y = y;
        this.length = length;
        this.width = width;
        this.radius = radius;
        this.color = color;
    }

    fill = function ( cxt ) {
        const point_a = Point( this.x + this.radius, this.y );
        const point_b = Point( this.x + this.length, this.y );
        const point_c = Point( this.x + this.length, this.y + this.width );
        const point_d = Point( this.x, this.y + this.width );
        const point_e = Point( this.x, this.y );

        let points = [ point_b, point_c, point_d, point_e, point_a ];

        cxt.save();

        cxt.beginPath();
        cxt.moveTo( point_a.x, point_a.y );
        for ( let i = 0; i < 4; i++ ) {
            cxt.arcTo( points[ i ].x, points[ i ].y, points[ i + 1 ].x, points[ i + 1 ].y, this.radius );
            // console.log("arc from (" + points[i].x + ',' + points[i].y + ") to (" + points[i + 1].x + ',' + points[i + 1].y + ")");
        }

        cxt.fillStyle = this.color;
        cxt.closePath();
        cxt.fill();
        // cxt.fillRect(this.x, this.y, this.width, this.height);
        cxt.restore();
    }

    is_touch_in_this( device ) {
        return inRange( device.x, this.x, this.x + this.length ) && inRange( device.y, this.y, this.y + this.width );
    }

    /**
     *
     * @param {RoundRectangle} other
     * @param {number} box_width 2 on default
     */
    IsCollideWith( other, box_width ) {
        box_width = box_width || 2;
        return isRangesCollide( this.x - box_width, this.x + this.length + box_width, other.x,
                other.x + other.length ) &&
            isRangesCollide( this.y - box_width, this.y + this.width + box_width, other.y, other.y + other.width );
    }
}